package com.mt.skyhoist;

import androidx.fragment.app.FragmentActivity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothGattCharacteristic;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentStatePagerAdapter;
import androidx.viewpager.widget.ViewPager;
import androidx.viewpager.widget.ViewPager.OnPageChangeListener;

import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;


import com.mt.skyhoist.ui.activity.Connect2Fragment;
import com.mt.skyhoist.ui.activity.ControlFragment;
import com.mt.skyhoist.ui.activity.HomeFragment;
import com.mt.skyhoist.util.GlobalVariable;
import com.mt.skyhoist.util.bean.DeviceModel;
import com.mt.skyhoist.util.view.ControlConfirmDialog2;
import com.mt.sdk.ble.MTBLEManager;
import com.mt.sdk.ble.base.MTSeriaBase;
import com.mt.sdk.ble.model.BLEBaseAction.Option;
import com.mt.sdk.ble.model.ErroCode;
import com.mt.sdk.ble.model.WriteCharactAction;


import org.greenrobot.eventbus.EventBus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

import com.mt.skyhoist.ui.activity.ScanDeviceService;
import com.mt.skyhoist.R;

/**
 * Created by daiguangtao on 2020/05/30.
 */
public class MainActivity extends FragmentActivity {
    private Logger log = LoggerFactory.getLogger("MainActivity");
    private GlobalVariable mGlobalVariable;
    private MTBLEManager manager;

    private List<DeviceModel> workingDevices = new ArrayList<DeviceModel>();
    //	private List<MTSeriaBase> bles = new ArrayList<MTSeriaBase>();
    private List<MTSeriaBase.CallBack> callbacks = new ArrayList<MTSeriaBase.CallBack>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mGlobalVariable = GlobalVariable.getinstance();
        manager = MTBLEManager.getInstance(getApplicationContext());

        startService();

        log.debug("onCreate");

        initFragment();

        initView();

        initBle();

//		initPhone();
    }

    private void startService() {
        Intent intent = new Intent(this, ScanDeviceService.class);
        startService(intent);
    }

    // 初始化控件
    private TextView fragmenttitle_txt;
    private RadioGroup menu_select_radiogrounp;
    private RadioButton[] radiobtns = new RadioButton[3];
    private RadioButton scandevice_btn;
    private RadioButton function_btn;
    private RadioButton home_btn;
    private ViewPager page_continer;

    private int autoChangeTimes = 0;
    private int userChangeTimes = -1;

    private void initView() {
        page_continer = (ViewPager) findViewById(R.id.page_continer);
        fragmenttitle_txt = (TextView) findViewById(R.id.fragmenttitle_txt);
        menu_select_radiogrounp = (RadioGroup) findViewById(R.id.menu_select_radiogrounp);
        scandevice_btn = (RadioButton) findViewById(R.id.scandevice_btn);
        function_btn = (RadioButton) findViewById(R.id.function_btn);
        home_btn = (RadioButton) findViewById(R.id.home_btn);

        radiobtns[0] = home_btn;
        radiobtns[1] = scandevice_btn;
        radiobtns[2] = function_btn;

        menu_select_radiogrounp.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {

                if (autoChangeTimes != 0) {
                    autoChangeTimes--;
                    return;
                }

                System.out.println("onCheckedChanged");
                userChangeTimes++;
                if (scandevice_btn.getId() == checkedId) {
                    gotoConnectFragment();
                    return;
                }

                if (function_btn.getId() == checkedId) {
                    gotoControlFragment();
                    return;
                }

                if (home_btn.getId() == checkedId) {
                    gotoHomeFragment();
                    return;
                }
            }
        });

        home_btn.setChecked(true);

        page_continer.setAdapter(mAdapter);

        page_continer.addOnPageChangeListener(new OnPageChangeListener() {

            @Override
            public void onPageSelected(int arg0) {
                if (userChangeTimes != 0) {
                    userChangeTimes--;
                    return;
                }
                System.out.println("onPageSelected->" + arg0);
                autoChangeTimes = 3;
                menu_select_radiogrounp.check(radiobtns[arg0].getId());
                switch (arg0) {
                    case 1:
                        fragmenttitle_txt.setText("SELECT");
                        break;
                    case 2:
                        fragmenttitle_txt.setText("CONTROL");
                        confirmDialog();
                        break;
                    case 0:
                        fragmenttitle_txt.setText("HOME");
                        break;
                }
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {

            }

            @Override
            public void onPageScrollStateChanged(int arg0) {

            }
        });
    }

    // 初始化fragment
    private FragmentManager fm;
    private HomeFragment homeFragment;
    private Connect2Fragment connectFragment;
    private ControlFragment controlFragment;
    private Fragment[] fragments = new Fragment[3];

    private void initFragment() {
        fm = getSupportFragmentManager();
        connectFragment = new Connect2Fragment();
        connectFragment.setCallback(connectFragmentCallback);

        controlFragment = new ControlFragment();
        homeFragment = new HomeFragment();

        fragments[0] = homeFragment;
        fragments[1] = connectFragment;
        fragments[2] = controlFragment;
    }

    private Connect2Fragment.ConnectFragmentCallback connectFragmentCallback = new Connect2Fragment.ConnectFragmentCallback() {
        @Override
        public void bindNewDevice(int index) {
        }

        @Override
        public void statuesChange(int index, boolean statues) {
            System.out.println("statuesChange->" + index + ", " + statues);
            disConnect(); // 先断开当前所有连接

            if (!statues) {
                return;
            }

            startConnect(index);
        }
    };

    private FragmentStatePagerAdapter mAdapter = new FragmentStatePagerAdapter(getSupportFragmentManager()) {

        @Override
        public int getCount() {
            return fragments.length;
        }

        @Override
        public Fragment getItem(int arg0) {
            return fragments[arg0];
        }

    };

    // 电话状态监听
    private TelephonyManager tm;

    private void initPhone() {
        tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);

        tm.listen(pl, PhoneStateListener.LISTEN_CALL_STATE);
    }

    private PhoneStateListener pl = new PhoneStateListener() {
        @Override
        public void onCallStateChanged(int state, String incomingNumber) {
            super.onCallStateChanged(state, incomingNumber);
            switch (state) {
                case TelephonyManager.CALL_STATE_RINGING:
//					mGlobalVariable.getMixDatas().setSelectgrounp(-1);
//					connectFragment.disconnect();
//					disConnect();
                    log.debug("CALL_STATE_RINGING");
                    controlFragment.stopAction();
                    break;  // 来电
                case TelephonyManager.CALL_STATE_OFFHOOK:
                    log.debug("CALL_STATE_OFFHOOK");
                    break; // 正在通话
                case TelephonyManager.CALL_STATE_IDLE:
                    log.debug("CALL_STATE_IDLE");
                    break;   // 挂断
                default:
                    break;
            }
        }
    };

    private void initBle() {
        setBroadCast();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            GrantLocationPermissionToApp();
        } else {
            requestEnableBLE();
        }


    }

    private static final int PERMISSION_REQUEST = 1;

    @TargetApi(Build.VERSION_CODES.M)
    public void GrantLocationPermissionToApp() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            if (this.checkSelfPermission(Manifest.permission.BLUETOOTH_SCAN) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.BLUETOOTH_SCAN,
                        Manifest.permission.BLUETOOTH_CONNECT,
                        Manifest.permission.BLUETOOTH_ADMIN}, PERMISSION_REQUEST);
            } else {
                requestEnableBLE();
            }
            return;
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (this.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_REQUEST);
            } else {
                requestEnableBLE();
            }
        }
    }

    // 请求开启蓝牙
    @SuppressLint("MissingPermission")
    private void requestEnableBLE() {
        if (!manager.isEnable()) {
            startActivityForResult(new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE), 0);
            return;
        }
        EventBus.getDefault().post(ScanDeviceService.StartScan);
        startConnect(mGlobalVariable.getMixDatas().getSelectgrounp());
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        log = LoggerFactory.getLogger("MainActivity");

        requestEnableBLE();
    }

    // 开启广播监听蓝牙
    private BroadcastReceiver receiver;
    private IntentFilter filter;

    private void setBroadCast() {
        receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) { // 蓝牙开关发生变化
                    if (intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1) == BluetoothAdapter.STATE_ON) { // 是使能蓝牙
                        System.out.println("使能了蓝牙");
                        handl.postDelayed(new Runnable() {
                            public void run() {
                                startConnect(mGlobalVariable.getMixDatas().getSelectgrounp());
                            }
                        }, 5000);
                    }
                    return;
                }
            }
        };

        filter = new IntentFilter();
        filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);

        registerReceiver(receiver, filter);
    }

    // 开始连接
    private void startConnect(int grounpid) {
        System.out.println("startConnect->"+grounpid);
        if ((!manager.isEnable()) || (grounpid == -1)) { // 没有开启蓝牙的话，就不要执行下面的动作
            return;
        }
        workingDevices.clear();
        for (DeviceModel i : mGlobalVariable.getDeviceList()) {
            System.out.println("DeviceModel->"+i.getGrounpId());
            if(i.getGrounpId() == grounpid){
                workingDevices.add(i);
            }
        }

        mGlobalVariable.bles.clear();
        callbacks.clear();

        for (int i = 0; i < workingDevices.size(); i++) {
            System.out.println("workingDevices->");
            MTSeriaBase ble = new MTSeriaBase(getApplicationContext(), manager);

            MTSeriaBase.CallBack callback = new MTSeriaBase.CallBack() {

                @Override
                public void reTryConnect(int lasttimes) {

                }

                @Override
                public void onManualDisConnect(ErroCode errocode) {

                }

                @Override
                public void onDisConnect(ErroCode errocode) {

                    interruptConnectStatues();

                    int i = -1;
                    for(int j=0; j<callbacks.size(); j++){
                        if(this == callbacks.get(j)){
                            i = j;
                            break;
                        }
                    }
                    if(i == -1){  // 如果没找到，说明已经过时了
                        return;
                    }

                    handl.removeMessages(i);
                    connectFragment.setConnectStatues(workingDevices.get(0).getGrounpId(), false);
                    if (isDestroyed() || !manager.isEnable()) { // 如果已经销毁，则不要重连
                        return;
                    }
                    String mac = workingDevices.get(i).getMac();
                    if ((mac == null) || (mac.equals(""))) {
                        return;
                    }
                    mGlobalVariable.bles.get(i).connect(mac, 2, false, callbacks.get(i));
                }

                @Override
                public void onDatasRecive(BluetoothGattCharacteristic rxd_charact, byte[] datas) {
                    if ((datas == null) || (datas.length != 2)) {
                        return;
                    }
//					if (datas[0] == 0x01) { // 温度
//						informationFragment.setTemp((datas[1] & 0xFF) - 128);
//						return;
//					}
//					if (datas[0] == 0x02) { // 湿度
//						informationFragment.setHumidity((datas[1] & 0xFF) - 128);
//						return;
//					}
                }

                @Override
                public void onConnect(ErroCode errocode) {
                    System.out.println("main onConnect->" + errocode.getMsg());
                    int i = -1;
                    for(int j=0; j<callbacks.size(); j++){
                        if(this == callbacks.get(j)){
                            i = j;
                            break;
                        }
                    }
                    if(i == -1){  // 如果没找到，说明已经过时了
                        return;
                    }

                    if ((errocode != null) && (errocode.getCode() == 0)) {
                        interruptConnectStatues();
                        System.out.println("main onConnect------------------------------->OK");
                        handl.sendEmptyMessage(i);
//						connectFragment.setConnectStatues(i, true);
                        return;
                    }

                    System.out.println("main onConnect->fail");
                    if (isDestroyed() || (!manager.isEnable())) { // 未选择的设备，不需要连接
                        return;
                    }

                    String mac = mGlobalVariable.getDeviceList().get(i).getMac();
                    if ((mac == null) || (mac.equals(""))) {
                        return;
                    }
                    mGlobalVariable.bles.get(i).connect(mac, 2, false, callbacks.get(i));
                    return;
                }
            };

            mGlobalVariable.bles.add(ble);
            callbacks.add(callback);
        }

        for (int i = 0; i < mGlobalVariable.bles.size(); i++) {
            System.out.println("开始连接->");
            if (mGlobalVariable.bles.get(i).isConnected()) { // 已经连接的设备，忽略
                continue;
            }
            String mac = workingDevices.get(i).getMac();
            if ((mac == null) || (mac.equals(""))) {
                continue;
            }
            mGlobalVariable.bles.get(i).connect(mac, 2, false, callbacks.get(i));
        }
    }

    // 断开所有连接
    private void disConnect(){
        allConnect = false;
        controlFragment.setConnectStatues(allConnect);
        for (int i = 0; i < mGlobalVariable.bles.size(); i++) {
            System.out.println("断开连接");
            mGlobalVariable.bles.get(i).disConnect();
        }
    }

    // 判断此时所有连接状态
    private boolean allConnect = false;
    private void interruptConnectStatues(){
        for (MTSeriaBase ble : mGlobalVariable.bles) {
            if(!ble.isConnected()){
                allConnect = false;
                controlFragment.setConnectStatues(allConnect);
                connectFragment.setConnectStatues(mGlobalVariable.getMixDatas().getSelectgrounp(), false);
                return;
            }
        }
        allConnect = true;
        controlFragment.setConnectStatues(allConnect);
        connectFragment.setConnectStatues(mGlobalVariable.getMixDatas().getSelectgrounp(), true);
    }

    // 跳转到连接界面
    private void gotoConnectFragment() {
        fragmenttitle_txt.setText("SELECT");
        page_continer.setCurrentItem(1);
    }

    // 跳转到控制界面
    private void gotoControlFragment() {
        fragmenttitle_txt.setText("CONTROL");

//		controlFragment.setBles(bles);

        page_continer.setCurrentItem(2);

        confirmDialog();
    }

    private ControlConfirmDialog2 dialog;
    private void confirmDialog(){
        dialog = new ControlConfirmDialog2(this);
        dialog.setMessage("IS THE LIFT LIGHT GREEN?");
        dialog.setCancelListener(new ControlConfirmDialog2.OnBtnClickListener() {
            @Override
            public void Onclick(View view) {
                gotoConnectFragment();
            }
        });
        dialog.show();
    }

    // 跳转到信息界面
    private void gotoHomeFragment() {
        fragmenttitle_txt.setText("HOME");
        page_continer.setCurrentItem(0);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);

        for (int i = 0; i < 8; i++) { // 移除掉所有的定时器
            handl.removeMessages(i);
        }

        for (MTSeriaBase ble : mGlobalVariable.bles) {
            ble.disConnect();
        }
    }

    private Handler handl = new Handler() {

        @Override
        public void handleMessage(Message msg) {

            super.handleMessage(msg);

            if (isDestroyed()) {
                return;
            }

            if(msg.what >= mGlobalVariable.bles.size()){
                return;
            }

            if (!mGlobalVariable.bles.get(msg.what).isConnected()) {
                return;
            }
            mGlobalVariable.bles.get(msg.what).addWriteDatasAction(new WriteCharactAction(null, new byte[] { 0x0A }, new Option(1000)));
            handl.sendEmptyMessageDelayed(msg.what, 5000); // 5秒钟发送一次
        }

    };
}
